from django.http import HttpResponse, JsonResponse
from django.core.cache import cache
from systemManage.models import Menu, MenuPermission
from django.forms import model_to_dict
import json


def index(request):
    return HttpResponse("Hello, world. You're at the system index.")


def get_menu(request):
    try:
        if request.method == 'GET':
            # 如果有缓存直接返回缓存
            if cache.get("menu"):
                return JsonResponse({"state": 200, "message": "查询成功", "data": cache.get("menu")}, safe=False)
            data = list(Menu.objects.all().values())
            for item in data:
                if item['higher']:
                    item["higher_text"] = Menu.objects.get(id=item['higher']).name
                else:
                    item["higher_text"] = '无上级菜单'
            # 设置缓存
            cache.set("menu", data)
            return JsonResponse({"state": 200, "message": "查询成功", "data": data}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("get_menu error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def add_menu(request):
    try:
        if request.method == 'POST' and request.body:
            new_data = json.loads(request.body)
            if new_data.get("name") and int(new_data.get("higher")) > -1 and new_data.get("path"):
                new_menu = Menu(**{"name": new_data["name"], "higher": new_data["higher"], "path": new_data["path"],
                                   "icon": new_data.get("icon") or ""})
                new_menu.save()
                # 移除get_menu获取列表的缓存
                cache.delete("menu")
                return JsonResponse({"state": 200, "message": "保存成功", "data": new_menu.id}, safe=False)
            else:
                return JsonResponse({"state": 500, "message": "参数缺失", "data": {}}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("add_menu error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def del_menu(request):
    try:
        if request.method == 'POST' and request.body:
            del_msg = json.loads(request.body)
            if del_msg.get("id"):
                Menu.objects.filter(id=del_msg["id"]).delete()
                # 移除get_menu获取列表的缓存
                cache.delete("menu")
                return JsonResponse({"state": 200, "message": "删除成功", "data": del_msg["id"]}, safe=False)
            else:
                return JsonResponse({"state": 500, "message": "参数缺失", "data": {}}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("del_menu error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def up_menu(request):
    try:
        if request.method == 'POST' and request.body:
            up_data = json.loads(request.body)
            if up_data.get("id"):
                res = Menu.objects.filter(id=up_data["id"])
                if len(res):
                    if up_data.get("name"):
                        res.update(name=up_data["name"])
                    if up_data.get("higher"):
                        res.update(higher=up_data["higher"])
                    if up_data.get("icon"):
                        res.update(icon=up_data["icon"])
                    if up_data.get("path"):
                        res.update(path=up_data["path"])
                    # 移除get_menu获取列表的缓存
                    cache.delete("menu")
                    return JsonResponse({"state": 200, "message": "保存成功", "data": up_data["id"]}, safe=False)
                else:
                    return JsonResponse({"state": 500, "message": "修改菜单不存在", "data": {}}, safe=False)
            else:
                return JsonResponse({"state": 500, "message": "参数缺失", "data": {}}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("up_menu error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def get_menu_template(request):
    try:
        if request.method == 'GET':
            # 如果有缓存直接返回缓存
            if cache.get("menuTemp"):
                return JsonResponse({"state": 200, "message": "查询成功", "data": cache.get("menuTemp")}, safe=False)
            data = list(MenuPermission.objects.all().values())
            # 设置缓存
            cache.set("menuTemp", data)
            return JsonResponse({"state": 200, "message": "查询成功", "data": data}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("get_menu_template error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def add_menu_template(request):
    try:
        if request.method == 'POST' and request.body:
            new_data = json.loads(request.body)
            if new_data.get("name") and int(new_data.get("permission")) > -1 and new_data.get("list"):
                per = MenuPermission.objects.filter(permission=new_data["permission"]).values()
                if len(per):
                    return JsonResponse({"state": 500, "message": "已经存在的权限等级", "data": {}}, safe=False)
                else:
                    new_menu = MenuPermission(**{"menu_name": new_data["name"], "permission": new_data["permission"], "menu_list": new_data["list"]})
                    new_menu.save()
                    # 移除get_menu_template获取列表的缓存
                    cache.delete("menuTemp")
                    return JsonResponse({"state": 200, "message": "保存成功", "data": new_menu.id}, safe=False)
            else:
                return JsonResponse({"state": 500, "message": "参数缺失", "data": {}}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("add_menu_template error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def del_menu_template(request):
    try:
        if request.method == 'POST' and request.body:
            del_msg = json.loads(request.body)
            if del_msg.get("id"):
                MenuPermission.objects.filter(id=del_msg["id"]).delete()
                # 移除get_menu_template获取列表的缓存
                cache.delete("menuTemp")
                return JsonResponse({"state": 200, "message": "删除成功", "data": del_msg["id"]}, safe=False)
            else:
                return JsonResponse({"state": 500, "message": "参数缺失", "data": {}}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("del_menu_template error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def up_menu_template(request):
    try:
        if request.method == 'POST' and request.body:
            up_data = json.loads(request.body)
            if up_data.get("id"):
                res = MenuPermission.objects.filter(id=up_data["id"])
                if len(res):
                    if up_data.get("permission"):
                        per = MenuPermission.objects.filter(permission=up_data["permission"]).values()
                        if len(per) and per.id != up_data["id"]:
                            return JsonResponse({"state": 500, "message": "已经存在的权限等级", "data": {}}, safe=False)
                        else:
                            res.update(permission=up_data["permission"])
                    if up_data.get("name"):
                        res.update(menu_name=up_data["name"])
                    if up_data.get("list"):
                        res.update(list=up_data["list"])
                    # 移除get_menu_template获取列表的缓存
                    cache.delete("menuTemp")
                    return JsonResponse({"state": 200, "message": "保存成功", "data": up_data["id"]}, safe=False)
                else:
                    return JsonResponse({"state": 500, "message": "修改菜单不存在", "data": {}}, safe=False)
            else:
                return JsonResponse({"state": 500, "message": "参数缺失", "data": {}}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("up_menu_template error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)